<template>
	<div style="max-width: 720px; margin: 24px auto;">
		<a-card title="个人中心">
			<a-form layout="vertical">
				<a-form-item label="头像">
					<SmartUpload v-model="avatar" file-type="image" :multiple="false" :max-count="1" button-text="上传头像" @uploaded="onAvatarUploaded" />
					<div v-if="avatar" style="margin-top:8px"><a-avatar :src="avatar" :size="64" /></div>
				</a-form-item>
				<a-form-item label="昵称">
					<a-input v-model:value="nickname" placeholder="请输入昵称" />
				</a-form-item>
				<a-form-item>
					<a-button type="primary" @click="saveNickname">保存昵称</a-button>
				</a-form-item>
			</a-form>
		</a-card>

		<a-card title="修改密码" style="margin-top: 16px;">
			<a-form layout="vertical">
				<a-form-item label="原密码"><a-input-password v-model:value="oldPassword" /></a-form-item>
				<a-form-item label="新密码"><a-input-password v-model:value="newPassword" /></a-form-item>
				<a-form-item>
					<a-button type="primary" @click="savePassword">修改密码</a-button>
				</a-form-item>
			</a-form>
		</a-card>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import SmartUpload from '@/components/SmartUpload.vue'
import { getProfile } from '@/api/admin'
import http from '@/api/http'

const nickname = ref('')
const avatar = ref<string>('')
const oldPassword = ref('')
const newPassword = ref('')

async function load() {
	try {
		const resp = await getProfile()
		if ((resp as any).code === 0) {
			nickname.value = (resp as any).data.nickname || ''
			avatar.value = (resp as any).data.avatar || ''
		}
	} catch {}
}

function onAvatarUploaded(url: string) {
	avatar.value = url
	saveAvatar()
}

async function saveNickname() {
	const resp = await http.put('/auth/profile/nickname', { nickname: nickname.value })
	if ((resp.data as any).code === 0) {
		message.success('昵称已更新')
		window.dispatchEvent(new CustomEvent('profile:updated', { detail: { nickname: nickname.value } }))
	}
}

async function saveAvatar() {
	if (!avatar.value) { message.warning('请先上传头像'); return }
	const resp = await http.put('/auth/profile/avatar', { avatar: avatar.value })
	if ((resp.data as any).code === 0) {
		message.success('头像已更新')
		window.dispatchEvent(new CustomEvent('profile:updated', { detail: { avatar: avatar.value } }))
	}
}

async function savePassword() {
	if (!newPassword.value) { message.warning('请填写新密码'); return }
	const resp = await http.put('/auth/profile/password', { oldPassword: oldPassword.value || undefined, newPassword: newPassword.value })
	if ((resp.data as any).code === 0) {
		message.success('密码已修改，将自动退出登录')
		oldPassword.value = ''
		newPassword.value = ''
		try { await http.post('/auth/logout') } catch {}
		localStorage.removeItem('token')
		setTimeout(() => { window.location.href = '/' }, 800)
	}
}

onMounted(load)
</script>


